﻿#if !UNITY_IOS || HUpdate
using FrameWork.Scripts.Module;
using SDK.Scripts.App;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.Networking;

namespace UnityModule
{
    public partial class DownloadComponent
    {
        //加载数组长度
        private int m_localResCount;
        //当前完成加载的个数
        private int m_localResLoadedNum;

        private Queue<AssetBundleInfo> m_bundleInfos;

        Action OnLocalResCopyFinish;

        /// <summary>
        /// key: 有hash的 abname, value: 无hash的 abname
        /// </summary>
        public readonly Dictionary<string, string> LocalBundleInfosWithHash = new Dictionary<string, string>();

        private byte[] m_bundleData;
        private int m_gameVersion;
        GFW_Report Report;
        int m_error = 0;
        public void LoadLocalRes(Action onFinish)
        {
            OnLocalResCopyFinish = onFinish;
            Report = SDK.Scripts.App.GameSDK.ModuleMgr.GetModule("GFW_Report") as GFW_Report;

            //检测gameversion
            m_gameVersion = SDK.Scripts.App.GameSDK.GamePlat.GameVersion;

            string localGameVersionPath = ApplicationPath.ABCachePath + ApplicationPath.BundleVersionFile;
            if (File.Exists(localGameVersionPath))
            {
                string context = File.ReadAllText(localGameVersionPath);
                int localVer = 0;
                int.TryParse(context, out localVer);
                if (localVer < m_gameVersion)//本地当前版本小于随包版本就解压
                {
                    CopyBundleFile();                    
                }
                else//更新当前版本
                {
                    m_gameVersion = localVer;
                    SDK.Scripts.App.GameSDK.GamePlat.GameVersion = m_gameVersion;
#if UNITY_IOS
                    IosStreamingAssetInfo(false);
#else
                    OnLocalResCopyFinish.Invoke();
#endif
                }
            }
            else
            {
                CopyBundleFile();
            } 
        }
        private void IosStreamingAssetInfo(bool saveFile = true)
        {
            //获取StreamingAsset 里的bundleinfo
            StartCoroutine(VersionComponent.LoadBundleBinInfo(ApplicationPath.WWWStreamingAssetsABPath + ApplicationPath.BundleInfoFile,
                (bundleBinInfo, data) =>
                {
                    m_bundleData = data;
                    foreach (var item in bundleBinInfo)
                    {
                        LocalBundleInfosWithHash[item.Value.abNameWithHash] = item.Key;
                    }
                    if(saveFile)
                    {
                        DirectoryTool.SaveFile(ApplicationPath.ABCachePath + ApplicationPath.BundleInfoFile, m_bundleData);
                        DirectoryTool.SaveFile(ApplicationPath.ABCachePath + ApplicationPath.BundleVersionFile, m_gameVersion.ToString());
                    }
                    OnLocalResCopyFinish?.Invoke();
                }, (error) =>
                {
                    OnLocalResCopyFinish?.Invoke();
                }));
        }
        public void CopyBundleFile()
        {
#if UNITY_IOS
            IosStreamingAssetInfo();
#else
            PanelLoad.Instance.ShowTxt("解压资源");            
            //获取StreamingAsset 里的bundleinfo
            StartCoroutine(VersionComponent.LoadBundleBinInfo(ApplicationPath.WWWStreamingAssetsABPath + ApplicationPath.BundleInfoFile,
                (bundleBinInfo,data) =>
                {
                    m_bundleData = data;
                    m_bundleInfos = new Queue<AssetBundleInfo>(bundleBinInfo.Values);

                    foreach (var item in bundleBinInfo)
                    {
                        LocalBundleInfosWithHash[item.Value.abNameWithHash] = item.Key;
                    }
                    m_localResCount = m_bundleInfos.Count;
                    m_localResLoadedNum = 0;
                    //SetStep(UpdateStepUtility.Step.LoadLocalRes, "解压资源");
                    //同时开始加载多个资源
                    for (int i = 0; i < 4; i++)
                    {
                        TryLoadOneLocalRes();
                    }
                }, (error) =>
                {
                    OnLocalResCopyFinish?.Invoke();
                }));
#endif

        }


        //开始加载一个资源
        private void TryLoadOneLocalRes()
        {
            if (m_bundleInfos.Count == 0)
            {
                return;
            }
            AssetBundleInfo item = m_bundleInfos.Dequeue();
            StartCoroutine(LoadOneLocalResEnumerator(item));
        }

        private IEnumerator LoadOneLocalResEnumerator(AssetBundleInfo item)
        {
            using (UnityWebRequest wwwGetInfo = UnityWebRequest.Get(ApplicationPath.WWWStreamingAssetsABPath + item.abNameWithHash))
            {
                yield return wwwGetInfo.SendWebRequest();
                
                if (string.IsNullOrEmpty(wwwGetInfo.error))
                {
                    string filePath = ApplicationPath.ABCachePath + item.abNameWithHash;
                    byte[] bytes = wwwGetInfo.downloadHandler.data;
                    string result = DirectoryTool.SaveFile(filePath, bytes);
                    if(string.IsNullOrEmpty(result))
                    {
                        PanelLoad.Instance.SetProgress(1.0f * m_localResLoadedNum / m_localResCount);
                        m_localResLoadedNum++;
                        //完成数等于加载数组长度时
                        if (m_localResLoadedNum == m_localResCount)
                        {
                            Report.SendEvent((int)ReportStep.startUnZipFile, "1");
                            VersionComponent.Instance.ClearOldBundle(LocalBundleInfosWithHash);
                            //保存下载好的bin文件,不管是已经在缓存目录，还是stream 目录，都再写一遍在缓存目录
                            string result1 = DirectoryTool.SaveFile(ApplicationPath.ABCachePath + ApplicationPath.BundleInfoFile, m_bundleData);
                            string result2 = DirectoryTool.SaveFile(ApplicationPath.ABCachePath + ApplicationPath.BundleVersionFile, m_gameVersion.ToString());
                            if (!string.IsNullOrEmpty(result1))
                            {
                                Report.SendEvent((int)ReportStep.startUnZipFile, result1 + ApplicationPath.BundleInfoFile);
                            }
                            if (!string.IsNullOrEmpty(result2))
                            {
                                Report.SendEvent((int)ReportStep.startUnZipFile, result2 + ApplicationPath.BundleVersionFile);
                            }
                            UnityEngine.Debug.LogError("解压完成" + m_gameVersion);
                            //加载完成
                            OnLocalResCopyFinish?.Invoke();
                        }
                    }
                    else
                    {
                        Report.SendEvent((int)ReportStep.startUnZipFile,result + item.abNameWithHash);
                        m_bundleInfos.Enqueue(item);
                        m_error++;
                    }                    
                }
                else
                {
                    Report.SendEvent((int)ReportStep.startUnZipFile, item.abNameWithHash + wwwGetInfo.error);
                    m_bundleInfos.Enqueue(item);
                    m_error++;
                }
                //尝试继续加载
                TryLoadOneLocalRes();        
                if(m_error > 10)
                {
                    PanelLoad.Instance.ShowTxt("解压失败,请重启游戏再试");
                    StopAllCoroutines();
                }
            }
        }
    }
}
#endif